package com.talent.controller;

import com.talent.common.PageResult;
import com.talent.common.Result;
import com.talent.pojo.dto.ResetPasswordDTO;
import com.talent.pojo.dto.UserDTO;
import com.talent.pojo.entity.User;
import com.talent.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/users")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 分页查询用户
     */
    @GetMapping
    public Result<PageResult<User>> pageQuery(@RequestParam(defaultValue = "1") Integer page,
                                              @RequestParam(defaultValue = "10") Integer pageSize,
                                              String search) {
        log.info("分页查询用户：page={}, pageSize={}, search={}", page, pageSize, search);
        PageResult<User> pageResult = userService.pageQuery(page, pageSize, search);
        return Result.success(pageResult);
    }

    /**
     * 根据ID查询用户
     */
    @GetMapping("/{id}")
    public Result<User> getById(@PathVariable Long id) {
        log.info("根据ID查询用户：{}", id);
        User user = userService.getById(id);
        return Result.success(user);
    }

    /**
     * 新增用户
     */
    @PostMapping
    public Result<String> save(@Valid @RequestBody UserDTO userDTO) {
        log.info("新增用户：{}", userDTO);
        userService.save(userDTO);
        return Result.success("新增成功");
    }

    /**
     * 更新用户
     */
    @PutMapping("/{id}")
    public Result<String> update(@PathVariable Long id, @Valid @RequestBody UserDTO userDTO) {
        log.info("更新用户：id={}, data={}", id, userDTO);
        userService.update(id, userDTO);
        return Result.success("更新成功");
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteById(@PathVariable Long id) {
        log.info("删除用户：{}", id);
        userService.deleteById(id);
        return Result.success("删除成功");
    }

    /**
     * 重置用户密码
     */
    @PutMapping("/{id}/reset-password")
    public Result<String> resetPassword(@PathVariable Long id, @Valid @RequestBody ResetPasswordDTO resetPasswordDTO) {
        log.info("重置用户密码：id={}", id);
        userService.resetPassword(id, resetPasswordDTO.getNewPassword());
        return Result.success("密码重置成功");
    }
}
